<?php
declare(strict_types=1);
namespace App\Dao;

use App\Model\Channel;
use App\Model\ChannelArea;

class ChannelAreaDao
{

    /**
     * 获取渠道的全部地区
     * @param $channelId
     * @param string[] $columns
     * @return array
     */
    public function getChannelAllArea($channelId, $columns=['*'])
    {
        return ChannelArea::query()->where(['channel_id' => $channelId, 'is_del' => 1])->get($columns)->toArray();
    }


    /**
     * 新建渠道地区
     * @param $insertArray
     * @return int
     */
    public function add($insertArray)
    {
        return ChannelArea::query()->insertGetId($insertArray);

    }

    /**
     * 删除渠道地区
     * @param $where
     * @return int
     */
    public function del($where)
    {
        return ChannelArea::query()->where($where)->delete();

    }


    /**
     * 查询
     * @param $id
     * @param string[] $columns
     * @return array
     */
    public function findById($id, $columns=['*'])
    {
        return ChannelArea::query()->find($id, $columns);
    }

    /**
     * 更新
     * @param $where
     * @param $updateArray
     * @return int
     */
    public function update($where, $updateArray)
    {
        return ChannelArea::query()->where($where)->update($updateArray);
    }

    /**
     * 查询渠道地区信息
     * @param $where
     * @param string[] $columns
     * @return array
     */
    public function findByWhere($where, $columns=['*'])
    {
        return ChannelArea::query()->where($where)->first($columns);
    }

    /**
     * 查询渠道信息
     * @param $type
     * @param $operatorType
     * @param $cityId
     * @param $rechargeAmountId
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object|null
     */
    public function findChannelByAmountArea($type, $operatorType, $cityId, $rechargeAmountId)
    {
        return ChannelArea::query()
            ->join('channel', 'channel_area.channel_id', '=', 'channel.id')
            ->join('recharge_amount_channel', 'channel_area.channel_id', '=', 'recharge_amount_channel.channel_id')
            ->where([
                'channel_area.type'=>$type,
                'channel_area.operator_type'=>$operatorType,
                'channel_area.city_id'=>$cityId,
                'channel_area.is_del'=>1,
                'recharge_amount_channel.recharge_amount_id'=>$rechargeAmountId,
                'recharge_amount_channel.status'=>2,
                'channel.status'=>1,
                'channel.is_del'=>1,

            ])->where('channel.start_time', '<', time())->orderBy('channel.sort', 'desc')
            ->first(['channel.*','recharge_amount_channel.cost']);
    }
}